package com.ytjj.qmyx.mall.controller;

import com.ytjj.common.api.CommonResult;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.controller.BaseController;
import com.ytjj.common.dto.mqdto.ClickStatisticsDto;
import com.ytjj.common.dto.mqdto.PageStatisticsDto;
import com.ytjj.common.enums.ScoreSourceEnum;
import com.ytjj.common.utils.IPUtil;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.mall.mapper.ProductQueryHistoryMapper;
import com.ytjj.qmyx.mall.mapper.ShareProductMapper;
import com.ytjj.qmyx.mall.model.ProductQueryHistory;
import com.ytjj.qmyx.mall.model.ShareProduct;
import com.ytjj.qmyx.mall.model.request.ClickStatisticsRequest;
import com.ytjj.qmyx.mall.model.request.PageStatisticsRequest;
import com.ytjj.qmyx.mall.model.request.QueryProductStatisticsRequest;
import com.ytjj.qmyx.mall.model.request.ShareStatisticsRequest;
import com.ytjj.qmyx.users.client.UsersClient;
import com.ytjj.qmyx.users.model.AddUserScoreRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.util.NamedThreadFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.*;

@Slf4j
@RestController
@RequestMapping("/statistics")
public class StatisticsController extends BaseController {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Resource
    private ShareProductMapper shareProductMapper;
    @Resource
    private UsersClient usersClient;
    @Resource
    private ProductQueryHistoryMapper productQueryHistoryMapper;

    Executor pools = new ThreadPoolExecutor(5, 10, 5,
            TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024 * 1024),
            new NamedThreadFactory("page_statistics_queue"),
            new ThreadPoolExecutor.DiscardOldestPolicy());

    /**
     * 页面统计
     * @param pageStatisticsRequest
     * @return
     */
    @PostMapping("/pageStatisticsData")
    public void pageAnalysisData(@RequestBody PageStatisticsRequest pageStatisticsRequest) {
        PageStatisticsDto pageStatisticsDto = new PageStatisticsDto();
        HttpServletRequest request = TokenUtil.getRequest();
        pageStatisticsDto.setUuid(request.getHeader("uuid"));
        pageStatisticsDto.setChannel(TokenUtil.getChannel());
        pageStatisticsDto.setModel(pageStatisticsRequest.getModel());
        pageStatisticsDto.setIp(IPUtil.getIpAddress(request));
        pageStatisticsDto.setFromPage(pageStatisticsRequest.getFromPage());
        pageStatisticsDto.setToPage(pageStatisticsRequest.getToPage());
        pageStatisticsDto.setParam(pageStatisticsRequest.getParam());
        pageStatisticsDto.setPlatform(TokenUtil.getSource());
        pageStatisticsDto.setCreateTime(new Date());
        try {
            pools.execute(() ->{
                rabbitTemplate.convertAndSend(QueueConstants.PAGE_STATISTICS_QUEUE,pageStatisticsDto);
            });
        } catch (Exception e) {
            log.error("===guobao pageStatisticsData send mq is error:{}", e);
        }

    }

    /**
     * 分享商品
     */
    @PostMapping("/shareStatisticsData")
    public CommonResult shareStatisticsData(@RequestBody ShareStatisticsRequest requst){
        ShareProduct shareProduct = new ShareProduct();
        shareProduct.setDataId(requst.getDataId());
        shareProduct.setType(requst.getType());
        shareProduct.setUuid(TokenUtil.getUuid());
        shareProduct.setCreateTime(new Date());
        shareProductMapper.insert(shareProduct);
        //分享商品看是否要加积分
        if(null != this.getH5CurrentUser() && this.getH5CurrentUser().getId() != null && requst.getType() == 1){
            String s = usersClient.addScore(new AddUserScoreRequest(this.getH5CurrentUser().getId(), ScoreSourceEnum.SHARE_PRODUCT,requst.getDataId()));
            return CommonResult.success(s);
        }
        return CommonResult.success();
    }

    /**
     * 点击统计
     * @param clickStatisticsRequest
     * @return
     */
    @PostMapping("/clikStatisticsData")
    public void clikStatisticsData(@RequestBody ClickStatisticsRequest clickStatisticsRequest) {
        ClickStatisticsDto clickStatisticsDto = new ClickStatisticsDto();
        HttpServletRequest request = TokenUtil.getRequest();
        clickStatisticsDto.setUuid(request.getHeader("uuid"));
        clickStatisticsDto.setChannel(TokenUtil.getChannel());
        clickStatisticsDto.setModel(clickStatisticsRequest.getModel().toJSONString());
        clickStatisticsDto.setIp(IPUtil.getIpAddress(request));
        clickStatisticsDto.setPlatform(TokenUtil.getSource());
        clickStatisticsDto.setClickType(clickStatisticsRequest.getClikType());
        clickStatisticsDto.setCreateTime(new Date());
        try {
            pools.execute(() -> {
                rabbitTemplate.convertAndSend(QueueConstants.CLICK_STATISTICS_QUEUE,clickStatisticsDto);
            });
        } catch (Exception e) {
            log.error("===guobao clikStatisticsData send mq is error:{}", e);
        }
    }


}
